package com.openatc.agent.config;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;

/**
 * @author ：panleilei
 * @description
 * @modified By：
 * @version:
 * @date ：Created in 2023/6/5 10:35
 */
@Configuration
public class CustomizeSchemaInitializer implements BeanPostProcessor {
    @Value("${schema:public}")
    private String schemaName;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @PostConstruct
    public void init() {
        String sql = "select " +
                " tc.constraint_name " +
                " from " +
                " information_schema.table_constraints AS tc " +
                " join information_schema.constraint_column_usage as ccu on ccu.constraint_name = tc.constraint_name " +
                " where " +
                " tc.table_name = 'vip_route' and column_name = 'name' and tc.constraint_type='UNIQUE'";
        // vip_route表的name字段的唯一约束名
        List<Map<String, Object>> constraint = jdbcTemplate.queryForList(sql);
        if (!CollectionUtils.isEmpty(constraint)) {
            Map<String, Object> stringObjectMap = constraint.get(0);
            String constraint_name = (String) stringObjectMap.get("constraint_name");
            // 删除唯一约束
            String deleteSql = "alter table vip_route drop constraint if exists " + constraint_name;
            jdbcTemplate.execute(deleteSql);
        }

    }
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        // 项目启动后，jpa数据库表创建前，创建schema
        if (bean instanceof JpaBaseConfiguration) {
            String auth2Sql = String.format("CREATE SCHEMA IF NOT EXISTS auth2 ");
//            String specialSchemaSql = String.format("CREATE SCHEMA IF NOT EXISTS %s ",schemaName);
            if ("public".equals(schemaName)) {
                jdbcTemplate.batchUpdate(auth2Sql);
            } else {
                String[] schemas = schemaName.split(",");
                String[] sqls = new String[schemas.length + 1];
                for (int i = 0; i < schemas.length; i++) {
                    sqls[i] = String.format("CREATE SCHEMA IF NOT EXISTS %s ",schemas[i]);
                }
                sqls[schemas.length] = auth2Sql;
                jdbcTemplate.batchUpdate(sqls);
            }
        }
        return BeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName);
    }
}
